﻿using System;
using System.Collections.Generic;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Web;

public class UserFactory
{
    private static UserFactory instance;
    private MysqlConnector connector;

    private UserFactory()
	{
        connector = MysqlConnector.getInstance();
	}

    public static UserFactory getInstance()
    {
        if (instance == null)
        {
            instance = new UserFactory();
        }
        return instance;
    }

    public User getUserById(int id)
    {
        String query = "SELECT * FROM user WHERE id = " + id;
        MySqlDataReader dr = connector.Select(query);

        User newUser = null;

        if (dr.HasRows)
        {
            dr.Read();
            newUser = new User(dr.GetString(1), dr.GetString(2));
            newUser.id = dr.GetInt32(0);
        }
        connector.CloseConnection();
        return newUser;
    }

    public User loginUser(String email, String password)
    {
        String hashedPass = Security.getInstance().encryptString(password);
        String query = "SELECT * FROM user WHERE email LIKE '" + 
            connector.cleanParam(email) + "' AND password LIKE '" + 
            hashedPass + "'";
        MySqlDataReader dr = connector.Select(query);

        User newUser = null;

        if (dr.HasRows)
        {
            dr.Read();
            newUser = new User(dr.GetString(1), dr.GetString(2));
            newUser.id = dr.GetInt32(0);
        }
        connector.CloseConnection();
        return newUser;
    }

    public void createUser(String email, String password, String name)
    {
        String query = "INSERT INTO user (email, password, name) VALUES('" +
            connector.cleanParam(email) + "', '" +
            Security.getInstance().encryptString(password) + "', '" +
            connector.cleanParam(name) + "')";
        connector.Insert(query);
    }

    public List<User> getUsersOnProject(int projectId)
    {
        String query = "SELECT * FROM user JOIN user_2_project u2p ON u2p.user = user.id WHERE u2p.project = " + projectId;
        MySqlDataReader dr = connector.Select(query);
        List<User> users = new List<User>();

        while (dr.Read())
        {
            User newUser = new User(dr.GetString(1), dr.GetString(2));
            newUser.id = dr.GetInt32(0);
            users.Add(newUser);
        }

        return users;
    }
}
